// TurnOffHdd.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "NotifyWnd.h"
#include "../Misc/LimitSingleInstance.h"

int mainImpl( HINSTANCE hInstance )
{
	CLimitSingleInstance instanceLimit( L"{125705B5-214B-4432-80CF-6CD327417C2A}" );
	if( instanceLimit.isAnotherInstanceRunning() )
	{
		::MessageBox( NULL, L"You can only have one instance running.\nThe application will now exit.", L"TurnOffHdd", MB_OK | MB_ICONERROR );
		return -1;
	}

	CComPtr<IVdsService> pService;
	HRESULT hr = vdsLoad( &pService );
	if( FAILED( hr ) )
	{
		::MessageBox( NULL, L"Unable to load Virtual Disk Service\n" + ErrorMessageW( hr ), L"TurnOffHdd", MB_OK | MB_ICONERROR );
		return hr;
	}

	CNotifyWnd wnd;
	hr = wnd.Create( pService, hInstance, MAKEINTRESOURCE( IDR_TRAY_MENU ) );
	if( FAILED( hr ) )
	{
		::MessageBox( NULL, L"Unable to create the icon\n" + ErrorMessageW( hr ), L"TurnOffHdd", MB_OK | MB_ICONERROR );
		return hr;
	}

	while( true )
	{
		MSG msg;
		const BOOL bRet = GetMessage( &msg, NULL, 0, 0 );
		if( 0 == bRet )
			return (int)msg.wParam;
		if( -1 == bRet )
		{
			::MessageBox( NULL, L"Error occurred\n" + ErrorMessageW( hr ), L"TurnOffHdd", MB_OK | MB_ICONERROR );
			return -1;
		}

		TranslateMessage( &msg );
		DispatchMessage( &msg );
	}
}

int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
	HRESULT hr = ::CoInitializeEx( NULL, COINIT_MULTITHREADED );
	if( FAILED( hr ) )
	{
		::MessageBox( NULL, L"CoInitializeEx failed\n" + ErrorMessageW( hr ), L"TurnOffHdd", MB_OK | MB_ICONERROR );
		return hr;
	}

	const int ret = mainImpl( hInstance );
	::CoUninitialize();
	return ret;
}